<?php

/**
 * 促销活动
 * @author Administrator
 */

namespace Partner\Controller;

use Operation\Model\Goods;
use Operation\Model\Game;
use Think\Controller;
use Think\IReq;
use Think\IFilter;
use Think\JSON;
use Think\Page;
use Think\ISafe;
use Think\Log;
use Think\IUpload;
use Think\IUrl;

class GameController extends ComController {

    //活动列表
    public function game_list() {
        $type_id = IFilter::act(IReq::get('type')) ? IFilter::act(IReq::get('type')) : 1;
        $p = IFilter::act(IReq::get('p')) ? IFilter::act(IReq::get('p')) : 1;
        $page = '20';
        $order = 'g.sort DESC';
        $gameObj = M('game as g');
        $join = 'sm_goods as go on g.goods_id = go.id';
        $field = 'g.id as id, g.title as title, go.name as name, g.start_time as start_time, g.end_time as end_time, g.is_close as is_close, g.sort as sort';
        $where = array(
            'g.type' => $type_id,
            'g.seller_id' => $this->Seller['seller_id']
        );
        $game = $gameObj->where($where)->field($field)->join($join)->order($order)->page($p, ',' . $page)->select();

        $count = $gameObj->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //dump($game);die;

        $this->assign('page', $show);
        $this->assign('list', $game);
        $this->assign('type_id', $type_id);
        $this->assign('name', Game::getName($type_id));
        $this->display();
    }

    //添加编辑活动
    public function game_edit() {
        $id = IFilter::act(IReq::get('id'), 'int');
        $type_id = IFilter::act(IReq::get('type_id'), 'int');

        if ($id) {
            $gameObj = M('game');
            $where = array(
                'id' => $id
            );
            $gameRow = $gameObj->where($where)->find();
            //dump($gameObj->getLastSql());
            //dump($gameRow);die;
            if (!$gameRow) {
                $this->redirect('game_list',array('type' => $type_id));
            }

            //活动商品
            $goodsObj = M('goods');
            $goodsRow = $goodsObj->where(array('id' => $gameRow['goods_id']))->field('id,img,name')->find();
            $goodsRow['start_id'] = $gameRow['start_id'];
            $goodsRow['end_id'] = $gameRow['end_id'];


            $result = array(
                'isError' => false,
                'data' => $goodsRow,
            );
            $gameRow['goodsRow'] = JSON::encode($result);

            $prizeRow = M('prize')->where(array('game_id' => $id))->select();
        }
        $type_id = $type_id ? $type_id : $gameRow['type'];
        
        //微信红包
        if($type_id == '3'){
            foreach ($prizeRow as $key => $value) {
                $prizeRow[$key]['prize_name'] = explode(':', $value['prize_name']);
            }
        }
        $gameRow = $this->gameRow ? $this->gameRow : $gameRow;
        //dump($gameRow);die;

        $this->assign('gameRow', $gameRow);
        $this->assign('json_game', JSON::encode($gameRow));
        $this->assign('prizeRow', $prizeRow);
        $this->assign('goodsRow', $gameRow['goodsRow'] ? $gameRow['goodsRow'] : 'null');
        $this->assign('name', Game::getName($type_id));
        $this->assign('type_id', $type_id);


        //优惠券
        $couponObj = M('coupon');
        $coupon = $couponObj->where(array('is_del' => 0))->select();
        $option = '';
        foreach($coupon as $value){
             $option .= '<option value="'.$value['id'].'">'.$value['title'].'</option>';
        }
        $this->assign('coupon', $coupon);
        $this->assign('option', $option);

        $sessionName = ISafe::name();
        $sessionId = ISafe::id();
        $this->assign('sessionName', $sessionName);
        $this->assign('sessionId', $sessionId);
        
        if($type_id == 3){
            $this->display('game_edit_hongbao');
        }else{
            $this->display();
        }
    }

    public function game_edit_act() {
        $id = IFilter::act(IReq::get('id'), 'int');
        $goodsId = IFilter::act(IReq::get('goods_id'), 'int');
        $type_id = IFilter::act(IReq::get('type_id', 'post'));
        //dump($_POST);die;

        if ($_FILES['Filedata']['size']) {
            //图片上传
            $upObj = new IUpload();

            //目录散列
            $dir = "./Public/Upload/game" . '/' . date('Y/m/d');
            $upObj->setDir($dir);
            $upState = $upObj->execute();
            header('Content-type: text/html; charset=UTF-8');
            $path = $upState['Filedata'][0]['flag'] == 1 ? $upState['Filedata'][0]['fileSrc'] : '';
        }
        $dataArray = array(
            'title' => IFilter::act(IReq::get('title', 'post')),
            'start_time' => IFilter::act(IReq::get('start_time', 'post')),
            'end_time' => IFilter::act(IReq::get('end_time', 'post')),
            'is_close' => IFilter::act(IReq::get('is_close', 'post')),
            'intro' => IFilter::act(IReq::get('intro', 'post')),
            'goods_id' => $goodsId,
            'num' => IFilter::act(IReq::get('num', 'post'), 'int'),
            'start_id' => IFilter::act(IReq::get('start_id', 'post'), 'int'),
            'end_id' => IFilter::act(IReq::get('end_id', 'post'), 'int'),
            'sort' => IFilter::act(IReq::get('sort', 'post')),
            'img' => $path,
            //'seller_id' => '',
            'prize' => '',
            'type' => $type_id,
            'failtext' => IFilter::act(IReq::get('failtext', 'post')),
            'is_del' => 0
        );


        if ($goodsId) {
            $goodsObj = M('goods');
            $where = array(
                'id' => $goodsId
            );
            $goodsRow = $goodsObj->where($where)->find();

            $dataArray['seller_id'] = $goodsRow['seller_id'];
        } else {
            $this->gameRow = $dataArray;
            $this->redirect('game_edit', array('type' => $type_id), 0, '请选择要关联的商品');
        }

        $gameObj = M('game');
        $prizeObj = M('prize');

        if ($id) {
            $dataArray['id'] = $id;
            $gameObj->save($dataArray);
            $res = $prizeObj->where(array('game_id' => $id))->delete();
            //dump($prizeObj->getLastSql());
            //dump($res);die;
        } else {
            $id = $gameObj->add($dataArray);
        }
        $data = array();
        //dump($_POST);die;
        if($type_id == '3'){
            //微信红包
            foreach ($_POST['prize'] as $key => $value) {
                $data[$key] = array(
                    'id' => $value['id'],
                    'prize_grade' => $value['name'],
                    'prize_name' => $value['content'][1] . ':' . $value['content'][2],
                    'chance' => $value['chance'],
                    'num' => $value['number'],
                    'type' => $value['type'],
                    'game_id' => $id
                );
            }
        }else{
            foreach ($_POST['prize'] as $key => $value) {
                $data[$key] = array(
                    'id' => $value['id'],
                    'prize_grade' => $value['name'],
                    'prize_name' => $value['content'],
                    'chance' => $value['chance'],
                    'num' => $value['number'],
                    'type' => $value['type'],
                    'game_id' => $id
                );
            }
        }
        
        $res = $prizeObj->addAll($data);
        //dump($prizeObj->getLastSql());
        //dump($res);die;
        $this->redirect('game_list', array('type' => $type_id));
    }

    //删除活动
    public function game_del() {
        $id = IFilter::act(IReq::get('id'), 'int');
    }
    
    //中奖纪录
    public function prize_list(){
        $type_id = IFilter::act(IReq::get('type_id')) ? IFilter::act(IReq::get('type_id')) : 1;
        $p = IFilter::act(IReq::get('p')) ? IFilter::act(IReq::get('p')) : 1;
        $page = '20';
        $order = 'd.time DESC, g.sort DESC, d.id DESC';
        $logObj = M('do_prize as d');
        $join = array(
            'sm_game as g on d.game_id = g.id',
            'sm_code as c on d.codeid = c.id',
            'sm_prize as p on d.prize_id = p.id'
            );
        $field = 'd.*, g.title as title, c.id as codeid, c.code as code, p.prize_grade as prize_grade, p.prize_name as prize_name, p.type as prize_type';
        $where = array(
            'g.type' => $type_id,
            'g.seller_id' => $this->Seller['seller_id']
        );
        $prizeLog = $logObj->where($where)->field($field)->join($join)->order($order)->page($p, ',' . $page)->select();

        foreach ($prizeLog as $key => $value) {
            switch ($value['prize_type']){
                case 1:
                    $c_where = array(
                        'c.id' => $value['prize_name'],
                        'cl.do_prize_id' => $value['id']
                        );
                    $c_join = array(
                        'sm_coupon_list as cl on c.id = cl.coupon_id'
                    );
                    $c_field = 'c.title as title, cl.coupon_code as coupon_code';
                    $coupon = M('coupon as c')->where($c_where)->join($c_join)->field($c_field)->find();
                    //dump(M()->getLastSql());
                    //dump($coupon);die;
                    $prizeLog[$key]['prize_name'] = $coupon['title'] . '：' . $coupon['coupon_code'];
                    break;
                case 2:
                    if(is_array($amount = explode(':', $value['prize_name']))){
                        if ($amount[0] == $amount[1]) {
                            $prizeLog[$key]['prize_name'] = '现金红包 ：' . $amount[0] . '元';
                        }  else {
                            $prizeLog[$key]['prize_name'] = '现金红包 ：' . $value['prize'] . '元';
                        }
                    }  else {
                        $prizeLog[$key]['prize_name'] = '现金红包 ：' . $value['prize_name'] . '元';
                    }
                    break;
                default :
                    $prizeLog[$key]['prize_name'] = $value['prize_name'];
                    break;
            }
        }
        $count = $logObj->where($where)->join($join)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //dump($game);die;

        $this->assign('page', $show);
        $this->assign('list', $prizeLog);
        $this->assign('type_id', $type_id);
        $this->assign('name', Game::getName($type_id));
        $this->display();
    }
    
    //未中奖纪录
    public function prize_no_list(){
        $type_id = IFilter::act(IReq::get('type_id')) ? IFilter::act(IReq::get('type_id')) : 1;
        $p = IFilter::act(IReq::get('p')) ? IFilter::act(IReq::get('p')) : 1;
        $page = '20';
        $order = 'd.time DESC, g.sort DESC, d.id DESC';
        $logObj = M('do_prize as d');
        $join = array(
            'sm_game as g on d.game_id = g.id',
            'sm_code as c on d.codeid = c.id'
            );
        $field = 'd.*, g.title as title, c.code as code';
        $where = array(
            'g.type' => $type_id,
            'g.seller_id' => $this->Seller['seller_id'],
            'd.prize_id' => 0
        );
        $prizeLog = $logObj->where($where)->field($field)->join($join)->order($order)->page($p, ',' . $page)->select();

        $count = $logObj->where($where)->join($join)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //dump($game);die;

        $this->assign('page', $show);
        $this->assign('list', $prizeLog);
        $this->assign('type_id', $type_id);
        $this->assign('name', Game::getName($type_id));
        $this->display();
    }

    //代金券列表
    public function coupon_list() {
        $p = IFilter::act(IReq::get('p')) ? IFilter::act(IReq::get('p')) : 1;
        $page = '20';
        $order = 'c.id DESC';
        $couponObj = M('coupon as c');
        $join = 'left join sm_goods as go on c.good_id = go.id';
        $field = 'c.id as id, c.title as title, go.name as name, c.start_time as start_time, c.end_time as end_time, c.value as value, c.total as total';
        $where = array(
            'c.is_del' => 0,
            'c.seller_id' => $this->Seller['seller_id']
        );
        $coupon = $couponObj->where($where)->field($field)->join($join)->order($order)->page($p, ',' . $page)->select();
        //dump($couponObj->getLastSql());

        $count = $couponObj->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //dump($coupon);die;

        $this->assign('page', $show);
        $this->assign('coupon', $coupon);
        $this->display();
    }

    //添加、编辑代金券
    public function coupon_edit() {
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $couponObj = M('coupon');
            $couponRow = $couponObj->find($id);
        }
        //dump($couponRow);die;
        $this->assign('couponRow', $couponRow);
        $this->assign('json_couponRow', JSON::encode($couponRow));

        $goods = M('goods')->field('id,name,spec_array')->where(array('is_del' => '0', 'seller_id' => $this->Seller['seller_id']))->select();
        foreach ($goods as $key => $value) {
            if ($value['spec_array']) {
                $arr = JSON::decode($value['spec_array']);
                $i = 0;
                foreach ($arr as $k => $v) {
                    $a[$i] = $v;
                    $a[$i]['value'] = JSON::encode(explode(',', $v['value']));
                    $i++;
                }
                $goods[$key]['spec_array'] = JSON::encode($a);
            }
        }
        //dump($goods);die;
        $this->assign('goods', $goods);
        $this->display();
    }

    public function coupon_edit_act() {
        $id = IFilter::act(IReq::get('id'), 'int');
        $dataArray = array(
            'title' => IFilter::act(IReq::get('title', 'post')),
            'value' => IFilter::act(IReq::get('value', 'post')),
            'start_time' => IFilter::act(IReq::get('start_time', 'post')),
            'end_time' => IFilter::act(IReq::get('end_time', 'post')),
            'good_id' => IFilter::act(IReq::get('good_id', 'post')),
            'total' => IFilter::act(IReq::get('total', 'post'), 'int'),
            'description' => IFilter::act(IReq::get('description', 'post')),
            'is_del' => 0,
            'time' => \Think\ITime::getTime(),
            'seller_id' => $this->Seller['seller_id']
        );
        //dump($dataArray);die;

        $couponObj = M('coupon');
        if ($id) {
            $dataArray['id'] = $id;
            $res = $couponObj->save($dataArray);
        } else {
            $res = $couponObj->add($dataArray);
            //Coupon::create();
        }
        if ($res) {
            $this->success('创建成功', U('Game/coupon_list'));
        } else {
            $this->error('创建失败', U('Game/coupon_edit', array('id' => $id)));
        }
    }

    /**
     * @brief 图片上传
     */
    public function img_upload() {
        //图片上传
        $upObj = new IUpload();

        //目录散列
        $dir = "./Public/Upload/game" . '/' . date('Y/m/d');
        $upObj->setDir($dir);
        $upState = $upObj->execute();
        header('Content-type: text/html; charset=UTF-8');
        //dump($upState);die;
        //判断上传是否成功，如果float=1则成功
        if ($upState['Filedata'][0]['flag'] == 1) {
            $result = array(
                'flag' => 1,
                'img' => $upState['Filedata'][0]['fileSrc']
            );
        } else {
            $result = array('flag' => $upObj->errorMessage($upState['Filedata'][0]['flag']));
        }

        echo JSON::encode($result);
    }

}